package com.google.code.sms.dao.schema;

import org.springframework.jdbc.core.*;

/**
 * Used for creating and updating the database schema.
 *
 * @author Scott Ware
 */
public abstract class Schema {

    /**
     * Executes this schema.
     *
     * @param template The JDBC template to use.
     */
    public abstract void execute(JdbcTemplate template);

    /**
     * Returns whether the given table exists.
     *
     * @param template The JDBC template to use.
     * @param table The table in question.
     * @return Whether the table exists.
     */
    protected boolean tableExists(JdbcTemplate template, String table) {
        try {
            template.execute("select 1 from " + table);
        } catch (Exception x) {
            return false;
        }
        return true;
    }

    /**
     * Returns whether the given column in the given table exists.
     *
     * @param template The JDBC template to use.
     * @param column The column in question.
     * @param table The table in question.
     * @return Whether the column exists.
     */
    protected boolean columnExists(JdbcTemplate template, String column, String table) {
        try {
            template.execute("select " + column + " from " + table + " where 1 = 0");
        } catch (Exception x) {
            return false;
        }
        return true;
    }
}
